package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.RedisService;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate template;
//    redisTemplate.opsForValue();　　//操作字符串
//    redisTemplate.opsForHash();　　 //操作hash
//    redisTemplate.opsForList();　　 //操作list
//    redisTemplate.opsForSet();　　  //操作set
//    redisTemplate.opsForZSet();　 　//操作有序set

    @GetMapping("set")
    public void set() {
        template.opsForValue().set("name", "yuelin");
        template.opsForValue().set("username", "15", 10, TimeUnit.SECONDS);
    }

    @GetMapping("get")
    public String get() {
        return template.opsForValue().get("name");
    }

    @GetMapping("setObject")
    public void setObject() {
        User user = new User();
        user.setAge(18);
        user.setUsername("xiaoshuai");
//        String json = JSONObject.toJSONString(user);
        String json = JSON.toJSONString(user);
        template.opsForValue().set("userJson", json);
    }

    @GetMapping("getObject")
    public String getObject() {
        String userJson = template.opsForValue().get("userJson");
        String username = template.opsForValue().get("username");
        Map map = JSON.parseObject(userJson, Map.class);
        User user = JSON.parseObject(userJson, User.class);
        return username;
    }

    @GetMapping("cache")
    public String cache() {
        return redisService.testCache();
    }

    @GetMapping("update")
    public String update() {
        return redisService.update();
    }

    @GetMapping("delete")
    public void delete() {
        redisService.delete();
    }
}
